import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

const USER_KEY = 'OA_USER_KEY'
const TOKEN_KEY = 'OA_TOKEN_KEY'

export const PermissionChoices = {
  // 所有权限
  ALL: 0b111,
  // 无需权限
  Staff: 0b000,
  // 需要董事会权限
  Boarder: 0b001,
  // 部门leader
  Leader: 0b010,
}


export const useAuthStore = defineStore('counter', () => {
  const _token = ref("")
  const _user = ref({})

  function setUserToken(user, token) {
    // 保存到对象上(内存)
    _user.value = user
    _token.value = token

    // 同时存储到浏览器(硬盘)localStorage,json对象先转化为字符串
    localStorage.setItem(USER_KEY, JSON.stringify(user))
    localStorage.setItem(TOKEN_KEY, token)

  }
  // 这里才是真正的外部访问的user
  // {}对象在if中等价于true,''等价与false
  // 注意浏览器刷新时会重新计算，因此不要直接从内存中读取
  let user = computed(() => {
    if(Object.keys(_user.value).length == 0){
      let user_str = localStorage.getItem(USER_KEY)
      if (user_str){
        _user.value = JSON.parse(user_str)
      }  
    }
    return _user.value
  })

  let token = computed(() => {
    if(!_token.value){
      let token_str = localStorage.getItem(TOKEN_KEY)
      if(token_str){
        _token.value = token_str
      }
    }
    return _token.value;
  })

  let is_logined = computed(() => {
    // 这里会计算user，由此保证value不为null
    if(Object.keys(user.value).length>0 && token.value){
      return true;
    }
    return false;
  })

  let clearUserToken = () => {
    _user.value = {}
    _token.value = ""
    localStorage.removeItem(TOKEN_KEY)
    localStorage.removeItem(USER_KEY)
  }

  let own_permissions = computed(() => {
    let _permission = PermissionChoices.Staff

    if(is_logined.value){
      if(user.value.department.name == "董事会"){
        // 按位或
        _permission |= PermissionChoices.Boarder 
      }
  
      if(user.value.department.leader_id == user.value.uid){
        _permission |= PermissionChoices.Leader
      }
      return _permission
    }
  })

  function has_permission(permissions, opt="|"){
    // opt代表权限设置规则为 或
    // own_permissions = 0b001
    // 计算属性也需要通过.value的方式获取值
     let results = permissions.map((permissions) => (permissions & own_permissions.value)==permissions)
    //  [true, true, false]
    if(opt == "|"){
      if(results.indexOf(true) >= 0){
        return true;
      }else{
        return false;
      }
    }else{
      if(results.indexOf(false) >= 0){
        return true;
      }else{
        return false;
      }
    }
  }

  return { user, token, setUserToken, is_logined, clearUserToken, has_permission }
})